<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
defineOptions({
  name: 'SearchIndex'
})
const onClickLeft = () => {
  router.go(-1)
}

// 组件挂载时从本地存储读取历史记录
onMounted(() => {
  const storedHistory = localStorage.getItem('searchHistory')
  history.value = storedHistory ? JSON.parse(storedHistory) : []
})
const searchValue = ref('')
const history = ref([])
const goSearch = (value) => {
  if (!value.trim()) return
  // 更新历史记录：去重 + 最新在前
  const updatedHistory = [
    value.trim(),
    ...history.value.filter(item => item !== value.trim())
  ].slice(0, 10)  // 最多保留10条
  
  history.value = updatedHistory
  // 存储到本地
  localStorage.setItem('searchHistory', JSON.stringify(updatedHistory))
  router.push(`/searchlist?search=${value}`)
}

// 清除历史记录
const clear = () => {
  history.value = []
  localStorage.removeItem('searchHistory')
}
</script>

<template>
  <van-nav-bar
    title="商品搜索"
    left-arrow
    @click-left="onClickLeft"
  />
  <van-search
    v-model="searchValue"
    show-action
    placeholder="请输入搜索关键词"
    clearable
  >
      <template #action>
        <div @click="goSearch(searchValue)">搜索</div>
      </template>
  </van-search>
  <!-- 搜索历史 -->
  <div class="search-history"  v-if="history.length > 0">
    <div class="title">
      <span>最近搜索</span>
      <van-icon @click="clear" name="delete-o" size="16" />
    </div>
    <div class="list">
      <div v-for="item in history" :key="item" class="list-item" @click="goSearch(item)">{{ item }}</div>
    </div>
  </div>
</template>

<style lang="less" scoped>
:deep(.van-nav-bar__title) {
  font-weight: normal;
}
:deep(.van-search__action) {
  background-color: #c21401;
  color: #fff;
  padding: 0 20px;
  border-radius: 0 5px 5px 0;
  margin-right: 10px;
}
:deep(.van-icon-arrow-left) {
  color: #333;
}
.title {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
}
.list {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  padding: 0 10px;
  gap: 5%;
}
.list-item {
  width: 30%;
  text-align: center;
  padding: 7px;
  line-height: 15px;
  border-radius: 50px;
  background: #fff;
  font-size: 13px;
  border: 1px solid #efefef;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin-bottom: 10px;
}

</style>